// 省份环比监控页面主逻辑

/**
 * 省份环比监控应用主类
 */
class ProvinceMonitorApp {
    constructor() {
        this.config = {
            refreshInterval: 5 * 60 * 1000, // 5分钟刷新
            apiEndpoint: '/api/tranvolume/province/compare'
        };
        
        this.timer = null;
        this.isUsingMockData = true;
        this.selectedProvinces = []; // 存储选中的省份
        
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            showLoading(true);
            
            // 初始化时间显示
            this.initTimeDisplay();
            
            // 初始化基准时间为当前时间
            this.initBaseTime();
            
            // 初始化省份选择器
            this.initProvinceSelector();
            
            // 初始化事件监听
            this.initEventListeners();
            
            // 检查API可用性
            await this.checkApiAvailability();
            
            // 加载初始数据
            await this.loadProvinceData();
            
            // 启动定时刷新
            this.startAutoRefresh();
            
            showLoading(false);
            updateStatus('success', '系统运行正常');
            
            log('info', '省份环比监控系统初始化完成');
        } catch (error) {
            handleError(error, '系统初始化');
            showLoading(false);
        }
    }

    /**
     * 初始化基准时间
     */
    initBaseTime() {
        const now = new Date();
        const timeString = now.toISOString().slice(0, 16);
        $('#provinceBaseTime').val(timeString);
    }

    /**
     * 初始化省份选择器
     */
    initProvinceSelector() {
        // 默认选择前5个省份
        const defaultProvinces = getAllProvinces().slice(0, 5);
        this.selectedProvinces = defaultProvinces.map(p => p.code);
        this.updateProvinceDisplay();
        this.renderProvinceGrid();
    }

    /**
     * 渲染省份网格
     */
    renderProvinceGrid(provinces = null) {
        const provinceList = provinces || getAllProvinces();
        const grid = $('#provinceGrid');
        grid.empty();
        
        provinceList.forEach(province => {
            const isSelected = this.selectedProvinces.includes(province.code);
            const isDisabled = !isSelected && this.selectedProvinces.length >= 5;
            
            const item = $(`
                <div class="province-item ${isSelected ? 'selected' : ''} ${isDisabled ? 'disabled' : ''}" 
                     data-code="${province.code}">
                    ${province.name}
                </div>
            `);
            
            if (!isDisabled) {
                item.on('click', () => this.toggleProvince(province.code));
            }
            
            grid.append(item);
        });
    }

    /**
     * 切换省份选择状态
     */
    toggleProvince(provinceCode) {
        const index = this.selectedProvinces.indexOf(provinceCode);
        
        if (index > -1) {
            // 取消选择
            this.selectedProvinces.splice(index, 1);
        } else {
            // 选择省份
            if (this.selectedProvinces.length < 5) {
                this.selectedProvinces.push(provinceCode);
            }
        }
        
        this.updateModalDisplay();
        this.renderProvinceGrid();
    }

    /**
     * 更新省份显示
     */
    updateProvinceDisplay() {
        const count = this.selectedProvinces.length;
        $('#selectedProvinceCount').text(count);
        
        const provincesList = $('#selectedProvincesList');
        provincesList.empty();
        
        this.selectedProvinces.forEach(code => {
            const provinceName = getProvinceName(code);
            const tag = $(`
                <span class="province-tag">
                    ${provinceName}
                    <button class="remove-btn" data-code="${code}">×</button>
                </span>
            `);
            
            tag.find('.remove-btn').on('click', (e) => {
                e.stopPropagation();
                this.removeProvince(code);
            });
            
            provincesList.append(tag);
        });
    }

    /**
     * 移除省份
     */
    removeProvince(provinceCode) {
        const index = this.selectedProvinces.indexOf(provinceCode);
        if (index > -1) {
            this.selectedProvinces.splice(index, 1);
            this.updateProvinceDisplay();
            this.loadProvinceData();
        }
    }

    /**
     * 更新模态框显示
     */
    updateModalDisplay() {
        $('#modalSelectedCount').text(this.selectedProvinces.length);
        
        const selectedNames = this.selectedProvinces.map(code => getProvinceName(code));
        $('#modalSelectedList').text(selectedNames.length > 0 ? selectedNames.join(', ') : '无');
    }

    /**
     * 初始化时间显示
     */
    initTimeDisplay() {
        const updateTime = () => {
            $('#currentTime').text(getCurrentTimeString());
        };
        
        updateTime();
        setInterval(updateTime, 1000);
    }

    /**
     * 初始化事件监听
     */
    initEventListeners() {
        // 省份环比查询条件
        $('#provinceBaseTime').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceTimeRange').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceCompareDays').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceCenterSelect').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));

        // 省份选择相关事件
        $('#provinceSearch').on('input', debounce((e) => {
            const keyword = e.target.value;
            const filteredProvinces = searchProvinces(keyword);
            this.renderProvinceGrid(filteredProvinces);
        }, 300));

        $('#confirmProvinceSelection').on('click', () => {
            this.updateProvinceDisplay();
            const modal = bootstrap.Modal.getInstance(document.getElementById('provinceModal'));
            modal.hide();
            this.loadProvinceData();
        });

        // 模态框显示时更新状态
        const provinceModal = document.getElementById('provinceModal');
        provinceModal.addEventListener('shown.bs.modal', () => {
            this.updateModalDisplay();
            $('#provinceSearch').val('').focus();
            this.renderProvinceGrid();
        });

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAutoRefresh();
            } else {
                this.resumeAutoRefresh();
            }
        });
    }

    /**
     * 检查API可用性
     */
    async checkApiAvailability() {
        try {
            const response = await $.ajax({
                url: '/api/tranvolume/health',
                method: 'GET',
                timeout: 3000
            });
            
            if (response && response.success) {
                this.isUsingMockData = false;
                log('info', 'API服务可用，使用真实数据');
                updateStatus('success', 'API连接正常');
            } else {
                throw new Error('API响应异常');
            }
        } catch (error) {
            this.isUsingMockData = true;
            log('warn', 'API服务不可用，使用模拟数据', error);
            updateStatus('error', '使用模拟数据');
        }
    }

    /**
     * 加载省份交易量环比数据
     */
    async loadProvinceData() {
        try {
            const baseTime = $('#provinceBaseTime').val();
            const timeRange = parseInt($('#provinceTimeRange').val()) || 60;
            const compareDays = parseInt($('#provinceCompareDays').val()) || 7;
            const center = $('#provinceCenterSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                data = this.generateDynamicProvinceData(baseTime, timeRange, compareDays);
            } else {
                const params = { 
                    baseTime, 
                    timeRange, 
                    compareDays, 
                    provinceCodes: this.selectedProvinces.join(','), 
                    center 
                };
                const response = await $.ajax({
                    url: this.config.apiEndpoint,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            createProvinceCompareChart('provinceChart', data);
            log('info', '省份交易量数据更新完成');
        } catch (error) {
            handleError(error, '省份交易量数据加载');
        }
    }

    /**
     * 根据查询条件生成动态省份数据
     */
    generateDynamicProvinceData(baseTime, timeRange, compareDays) {
        const allProvinces = getAllProvinces();
        
        // 根据选中的省份代码过滤
        const filteredProvinces = this.selectedProvinces.length > 0 ? 
            allProvinces.filter(p => this.selectedProvinces.includes(p.code)) : 
            allProvinces.slice(0, 5);

        // 生成指定天数的数据
        const dateData = [];
        const baseDate = baseTime ? new Date(baseTime) : new Date();
        
        for (let i = compareDays - 1; i >= 0; i--) {
            const currentDate = new Date(baseDate.getTime() - i * 24 * 60 * 60 * 1000);
            const dateStr = currentDate.toLocaleDateString('zh-CN', { 
                month: '2-digit', 
                day: '2-digit' 
            });
            
            // 为每个日期生成各省份的交易量数据，考虑时间范围
            const timeMultiplier = timeRange / 60;
            const provinceData = filteredProvinces.map(prov => ({
                provCode: prov.code,
                provName: prov.name,
                code: prov.code,
                name: prov.name,
                value: Math.floor((Math.random() * 2000 + 800 + i * 50) * timeMultiplier)
            }));

            dateData.push({
                date: dateStr,
                provinceData: provinceData
            });
        }

        return {
            provinces: filteredProvinces.map(p => ({
                ...p,
                provCode: p.code,
                provName: p.name
            })),
            dateData: dateData,
            updateTime: new Date().toLocaleString('zh-CN')
        };
    }

    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        this.timer = setInterval(() => {
            this.loadProvinceData();
        }, this.config.refreshInterval);
        
        log('info', '省份环比数据自动刷新已启动');
    }

    /**
     * 暂停自动刷新
     */
    pauseAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        log('info', '省份环比数据自动刷新已暂停');
    }

    /**
     * 恢复自动刷新
     */
    resumeAutoRefresh() {
        if (!this.timer) {
            this.startAutoRefresh();
            log('info', '省份环比数据自动刷新已恢复');
        }
    }

    /**
     * 销毁应用
     */
    destroy() {
        this.pauseAutoRefresh();
        chartManager.disposeAll();
        log('info', '省份环比监控应用已销毁');
    }
}

// 全局省份监控应用实例
let provinceMonitorApp;

// 文档加载完成后初始化应用
$(document).ready(function() {
    provinceMonitorApp = new ProvinceMonitorApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (provinceMonitorApp) {
        provinceMonitorApp.destroy();
    }
});